<?php
declare(strict_types=1);

namespace App\Controller;

use Hyperf\HttpServer\Annotation\AutoController;
use App\Model\User;

// use Hyperf\Nacos\Application;
// use Hyperf\Nacos\Config;
// use Hyperf\Codec\Json;
// use Hyperf\Config\Annotation\Value;

#[AutoController]
class BaseController
{
    // #[Value("nacos")]
    // private $configValue;

    /**
     * 检查令牌
     */
    public function Auth($request, $isToken=0)
    {
        $headers = $request->getHeaders();
        if (isset($headers['authorization'])) {
            $header = $headers['authorization'][0]; // 获取 Authorization 头部的第一个值
            if (strpos($header, 'Bearer ') === 0) {
                $token = substr($header, 7); // 去掉 "Bearer " 部分，获取实际的 token 值
                $userInfo = User::query()->where('token', $token)->first();
                if (!empty($userInfo)) {
                    if (strtotime($userInfo->tokenExpiration) > time()) {  // token没过期
                        // Token 未过期，更新过期时间
                        $expirationTime = date('Y-m-d H:i:s', time() + 60 * 60 * 24);
                        $userInfo->tokenExpiration = $expirationTime;
                        $userInfo->save();
                
                        $res['err'] = 0;
                        $res['msg'] = 'token没过期，跳转页面';
                        if ($isToken == 1) {
                            $res['token'] = $token;
                            $res['id'] = $userInfo->id;
                            $res['balance'] = $userInfo->balance;
                            $res['nickname'] = $userInfo->nickname;
                        }
                    } else {  // token过期
                        $res['err'] = 1;
                        $res['msg'] = 'token已过期，重新登录';
                    }
                } else {
                    $res['err'] = 1;
                    $res['msg'] = 'token已失效，重新登录';
                }
            } else {  // 处理错误的 Authorization 格式
                $res['err'] = 1;
                $res['msg'] = '错误的 Authorization 格式，重新登录';
            }
        } else {
            $res['err'] = 1;
            $res['msg'] = 'Authorization 头部不存在，重新登录';
        }
        return json_encode($res);
    }

    //   public function getNacos($id,$group){
        // $application = new Application(new Config($this->configValue));
        // $response = $application->config->get($id, $group);
        // $result = Json::decode((string) $response->getBody());
        // return $result;
  //   }
}
